//
//  SAPaymentWKWebVC.m
//  saasRetail
//
//  Created by mac on 2023/7/2.
//

#import "SAPaymentWKWebVC.h"
#import "HDWKWebView.h"
#import "SAGrowthCreateOrderAPI.h"
#import "SACreateOrderModel.h"
#import <WechatOpenSDK/WXApi.h>
#import "SAGrowthQueryStatusAPI.h"

@interface SAPaymentWKWebVC ()<HTTPAPIDelegate>

@property (nonatomic, strong) NSString *url;
@property (nonatomic, strong) UIButton *backBtn;
@property (nonatomic, strong) SAGrowthCreateOrderAPI *growthCreateOrderAPI;
@property (nonatomic, strong) SACreateOrderModel *orderModel;
@property (nonatomic, strong) SAGrowthQueryStatusAPI *growthQueryStatusAPI;
@property (nonatomic, strong) NSTimer *timer;

@end

@implementation SAPaymentWKWebVC

- (void)viewDidLoad {
    [super viewDidLoad];
}

-(instancetype)initWithTitle:(NSString *)title AndUrl:(NSString *)url {
    if (self =  [super init]) {
        self.url = url;
        [self initUI];
    }
    return self;
}

#pragma mark - HTTPAPIDelegate
- (void)fetchData:(id)data fromServerSuccessedWithAPI:(HTTPAPI *)api {
   if (self.growthCreateOrderAPI == api) {
        self.orderModel = [SACreateOrderModel mj_objectWithKeyValues:data[@"data"]];
        [self wxPayOrder];
       [self.timer invalidate];
       self.timer = nil;;
       self.timer = [NSTimer scheduledTimerWithTimeInterval:5 target:self selector:@selector(timerFired) userInfo:nil repeats:YES];
   }else if (self.growthQueryStatusAPI == api) {
       NSString *status = [NSString stringWithFormat:@"%@",data[@"data"][@"status"]];
       if ([status isEqualToString:@"2"]) {
           [Prompt popPromptViewWithMsg:@"支付成功" duration:2];
           !self.successedBlock ?: self.successedBlock(@"1");
           [self.timer invalidate];
           self.timer = nil;;
           [self.navigationController popViewControllerAnimated:YES];
       }
   }
}

- (void)fetchDataFromServerFailedWithError:(NSError *)error API:(HTTPAPI *)api {

}

#pragma mark - event
- (void)timerFired {
    self.growthQueryStatusAPI.orderNo = self.orderModel.orderNo;
    [self.growthQueryStatusAPI sendRequestToServerWithType:GET];
}

//微信支付订单
-(void)wxPayOrder {
    
    PayReq *rep = [[PayReq alloc] init];
    if ([WXApi isWXAppInstalled]) {
        rep.openID = self.orderModel.appid;
        rep.partnerId = self.orderModel.partnerId;
        rep.prepayId = self.orderModel.prepayId;
        rep.package = self.orderModel.packageValue;
        rep.nonceStr = self.orderModel.noncestr;
        rep.timeStamp = [self.orderModel.timestamp intValue];
        rep.sign = self.orderModel.sign;
        [WXApi sendReq:rep completion:^(BOOL success) {
            
        }];
    }else {
        dispatch_async(dispatch_get_main_queue(), ^{
            [Prompt popPromptViewWithMsg:@"请安装微信客户端" duration:2];
        });
    }
}

-(void)backToLastVC {
    !self.successedBlock ?: self.successedBlock(@"0");
    [self.timer invalidate];
    self.timer = nil;;
    [self.navigationController popViewControllerAnimated:YES];
}

#pragma mark - initUI
-(void)initUI {
    
    HDWKWebView *webView = [[HDWKWebView alloc] initWithConfig:@[@"NativeInterface"] frame:CGRectMake(0, 0, kScreenWidth, kScreenHeight)];
    webView.url = self.url;
    webView.isAdaptive = YES;
    [webView startLoadUrl];
    WeakSelf
    webView.jsActionBlock = ^(NSString *name, id body) {
        if ([name isEqualToString:@"NativeInterface"]) {
            NSString *str = [NSString stringWithFormat:@"%@",body[@"growthServiceId"]];
            [weakSelf createOrder:str];
        }
    };
    [self.view addSubview:webView];

    [self.view addSubview:self.backBtn];
}

//创建订单
-(void)createOrder:(NSString *)serviceId {
    self.growthCreateOrderAPI.growthServiceid = serviceId;
    [self.growthCreateOrderAPI sendRequestToServerWithType:POST];
}

- (UIButton *)backBtn
{
    if (!_backBtn){
        _backBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        [_backBtn setImage:[UIImage imageNamed:@"whiteAllow"] forState:UIControlStateNormal];
        [_backBtn addTarget:self action:@selector(backToLastVC) forControlEvents:UIControlEventTouchUpInside];
        _backBtn.titleLabel.font = kFont(18);
        _backBtn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
        _backBtn.imageEdgeInsets = UIEdgeInsetsMake(0, 15, 0, 0);
        _backBtn.titleEdgeInsets = UIEdgeInsetsMake(0, 15, 0, 0);
        _backBtn.frame = SARectMake(0, StatusHeight - 44, 50, 50);
    }
    return _backBtn;
}

-(SAGrowthCreateOrderAPI *)growthCreateOrderAPI {
    if (!_growthCreateOrderAPI) {
        _growthCreateOrderAPI = [SAGrowthCreateOrderAPI apiWithDelegate:self];
    }
    return _growthCreateOrderAPI;
}

-(SAGrowthQueryStatusAPI *)growthQueryStatusAPI {
    if (!_growthQueryStatusAPI) {
        _growthQueryStatusAPI = [SAGrowthQueryStatusAPI apiWithDelegate:self];
    }
    return _growthQueryStatusAPI;
}

@end
